package com.vae.auth.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.vae.auth.domain.XcUser;
import com.vae.auth.dto.AuthParamsDto;
import com.vae.auth.dto.XcUserExt;
import com.vae.auth.feignclient.CheckCodeClient;
import com.vae.auth.mapper.XcUserMapper;
import com.vae.auth.service.AuthService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.apache.commons.lang.StringUtils;
/**
 * @author: 35238
 * 功能: 账号密码模式认证
 * 时间: 2024-07-04 23:41
 */
@Service("password_authservice")//指定bean的名称，在UserServiceImpl里面有使用到这个bean名称，注意bean名称是"xx_authservice"的格式
public class PasswordAuthServiceImpl implements AuthService {

    @Autowired
    XcUserMapper xcUserMapper;

    @Autowired
    //密码的加密方式
    PasswordEncoder passwordEncoder;
    @Autowired
    CheckCodeClient checkCodeClient;

    @Override
    public XcUserExt execute(AuthParamsDto authParamsDto) {

        //校验验证码
        String checkcode = authParamsDto.getCheckcode();
        String checkcodekey = authParamsDto.getCheckcodekey();

        if(StringUtils.isBlank(checkcodekey) || StringUtils.isBlank(checkcode)){
            throw new RuntimeException("验证码为空");

        }
        Boolean verify = checkCodeClient.verify(checkcodekey, checkcode);
        if(!verify){
            throw new RuntimeException("验证码输入错误");
        }

        //账号
        String username = authParamsDto.getUsername();
        XcUser user = xcUserMapper.selectOne(new LambdaQueryWrapper<XcUser>().eq(XcUser::getUsername, username));
        if(user==null){
            //返回空表示用户不存在
            throw new RuntimeException("账号不存在");
        }
        XcUserExt xcUserExt = new XcUserExt();
        BeanUtils.copyProperties(user, xcUserExt);
        //校验密码
        String passwordDb  =user.getPassword();//数据库的正确密码
        String passwordForm = authParamsDto.getPassword();//用户输入的密码
        boolean matches = passwordEncoder.matches(passwordForm, passwordDb);//手动校验密码对不对
        if(!matches){
            throw new RuntimeException("账号或密码错误");
        }
        return xcUserExt;
    }
}
